#!/bin/bash
# Author: Xun Deng

### Prepare
. setup.sh # source
if [ -z "${DXOS_OSNAME}" ]; then
    echo 'setup error'
    exit 2
fi

### Make grub-core
if ! [ -d 'grub-core' ]; then
    rm -rf grub/
    gb="grub-${DXOS_GRUB_CORE_VERSION}"
    [ -f "${gb}.tar.xz" ] || wget "ftp://alpha.gnu.org/gnu/grub/${gb}.tar.xz"
    tar -xJpf "${gb}.tar.xz" -C grub && cd grub
    mkdir efi64 && cd efi64
    # work dir is 'grub/efi64/'
    ../configure --target=x86_64 --with-platform=efi && make -j64 && make install
    cd ../..
    cp -r grub/efi64/grub-core .
fi

### grub-install
# make sure "${DXOS_GRUB_DEVICE}1" is a FAT32 partition
par="${DXOS_GRUB_DEVICE}1"
if [ 1 -ne $(file -s "${par}" | grep -c 'FAT (32 bit)') ]; then
    echo "'${par}' is not a FAT partition"
    exit 4
fi

mount "${par}" /mnt
grub-install -d 'grub-core' --force --removable --no-floppy --target=x86_64-efi --boot-directory=/mnt/boot --efi-directory=/mnt
cat <<EOF >/mnt/boot/grub/grub.cfg
set timeout=3
set default=0
insmod all_video
loadfont unicode
terminal_output gfxterm
menuentry "${DXOS_OSNAME}" {
  linux /boot/bzImage
  initrd /boot/initrd.img
}
EOF
cp bzImage initrd.img /mnt/boot/
umount /mnt
